package com.seaboxdata.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


public class SignatureUtil {

	public final  static  String PASSID="dpxqzsj";  //分配的passid
	public final  static String TOKEN="fvQHd9b6xHOlpNJNv8JGDDf5MtPHK0ng";//分配的token

	/**
	 * 生成签名
	 * @param token
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static String genSignature(String timestamp,String nonce )
	{
		return sha256(timestamp+TOKEN+nonce+timestamp).toUpperCase();
	}
	private static String sha256(final String strText)
	{
	    // 返回值
	    String strResult = null;

	    // 是否是有效字符串
	    if (strText != null && strText.length() > 0)
	    {
	      try
	      {
	        // SHA 加密开始
	        // 创建加密对象 并傳入加密類型
	        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
	        // 传入要加密的字符串
	        messageDigest.update(strText.getBytes());
	        // 得到 byte 類型结果
	        byte byteBuffer[] = messageDigest.digest();

	        // 將 byte 轉換爲 string
	        StringBuffer strHexString = new StringBuffer();
	        // 遍歷 byte buffer
	        for (int i = 0; i < byteBuffer.length; i++)
	        {
	          String hex = Integer.toHexString(0xff & byteBuffer[i]);
	          if (hex.length() == 1)
	          {
	            strHexString.append('0');
	          }
	          strHexString.append(hex);
	        }
	        // 得到返回結果
	        strResult = strHexString.toString();
	      }
	      catch (NoSuchAlgorithmException e)
	      {
	        e.printStackTrace();
	      }
	    }

	    return strResult;
	}

	/**
	 * 取得当前时间戳
	 * @return
	 */
	public static String getTs() {
        long time = System.currentTimeMillis();
        String nowTimeStamp = String.valueOf(time / 1000);
        return nowTimeStamp;
    }

	public static String getNonce()
	{
    	long ts=System.currentTimeMillis();
		Random r=new Random(ts);
		long rvalue=r.nextLong();
		return rvalue+""+ts;
	}
}
